var list = []
//添加商品
function add(goods) {
  if (getPosition(goods) == -1) {
    goods.num = 1
    goods.isSelect = false
    list.push(goods)
    wx.setStorageSync('cart', list)
    return true
  }
  return false
}
//移除指定下标商品
function removeByPosition(position) {
  list.splice(position, 1)
}
//移除指定集合内的商品
function removes(arr) {
  for (var i = 0; i < list.length; i++) {
    var goods = list[i]
    if(contains(goods,arr)){
      list.splice(i,1)
      i--
    }
  }
  wx.setStorageSync('cart', list)
}

function contains(goods, arr) {
  for (var i = 0; i < arr.length; i++) {
    if(arr[i].pid==goods.id&&arr[i].type==goods.type){
      return true
    }
  }
  return false
}
//修改商品数量 num>0递增 小于0递减
function updateNum(position, num) {
  var obj = list[position]
  obj.num = obj.num + num
  if (obj.num == 0) obj.num = 1
  if (obj.num > 99) obj.num = 99
  wx.setStorageSync('cart', list)
}
//商品选择状态
function updateSelect(position) {
  var isSelect = !list[position].isSelect
  list[position].isSelect = isSelect
  wx.setStorageSync('cart', list)
  return isSelect

}
//全选
function allSelect(isSelect) {
  for (var i = 0; i < list.length; i++) {
    list[i].isSelect = isSelect
  }
  wx.setStorageSync('cart', list)
}
//判断商品所在下标
function getPosition(goods) {
  for (var i = 0; i < list.length; i++) {
    if (list[i].id == goods.id && list[i].type == goods.type) return i
  }
  return -1
}
//获取购物车里的商品
function getGoods() {
  return list;
}
//选中商品
function getSelectGoods() {
  var temps = []
  for (var i = 0; i < list.length; i++) {
    if (list[i].isSelect) temps.push(list[i])
  }
  return temps;
}
//商品总价
function getSumPrice() {
  var price = 0;
  for (var i = 0; i < list.length; i++) {
    if (list[i].isSelect) price += list[i].price * list[i].num
  }
  return price;
}
//初始化购物车,获取缓存数据
function initCart() {
  list = wx.getStorageSync("cart") || [];
  for (var i = 0; i < list.length; i++) {
    list[i].isSelect = false
  }
  wx.setStorageSync("cart", list)
}
module.exports = {
  add: add,
  removeByPosition: removeByPosition,
  removes: removes,
  updateNum: updateNum,
  updateSelect: updateSelect,
  getPosition: getPosition,
  getGoods: getGoods,
  getSelectGoods: getSelectGoods,
  allSelect: allSelect,
  getSumPrice: getSumPrice,
  initCart: initCart,
}